﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GoodStuff;

namespace GoodStuff.Heartbeat.Core.Configuration
{
    /// <summary>
    /// Apply this attribute to a class member to be able to configure it through XML
    /// </summary>
    public class ParameterAttribute : Attribute
    {
        public ParameterAttribute()
        {
        }

        public ParameterAttribute(bool required)
        {
            IsRequired = required;
        }

        public bool IsRequired { get; set; }

        public static void ApplyParameters(object target, IDictionary<string, string> parameters)
        {
            //find all members that have this attribute applied.
            var properties = target.GetProperties<ParameterAttribute>();         

            foreach (var property in properties)
            {
                var attribute = property.GetAttribute<ParameterAttribute>();

                if (parameters.ContainsKey(property.Name))
                {
                    var parameter = parameters.Single(p => p.Key == property.Name);

                    Type parameterType = property.PropertyType;
                    var typedValue = Convert.ChangeType(parameter.Value, parameterType);
                    property.SetValue(target, typedValue, null);
                }
                else
                {
                    if (attribute.IsRequired)
                    {
                        throw new ArgumentException("The parameter is required");
                    }
                }
            }
        }
    }
}
